/*
 * ============================================================================
 *
 *       Filename:  system.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2014年08月19日 10时19分07秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
/* netdevice */
#include <sys/ioctl.h>
#include <net/if.h>

/* hostbyname */
#include <netdb.h>
#include <sys/socket.h>

#include "common.h"
#include "netdev.h"
#include "system.h"
#include "log.h"

struct system_t gconf={{0}};

#ifdef CONFIG_AC
static void getip(char *nic, struct sockaddr_in *addr)
{
	getaddr(nic, SIOCGIFADDR, addr);
}

void gconf_init(char *nic, char *acaddr, int port)
{
	char macstr[MACSTR_LEN];
	getmac(nic, &gconf.mac[0]);
	if(acaddr) {
		if(!inet_aton((const char *)acaddr, &gconf.addr.sin_addr)) {
			sys_err("acaddr: %s is not a vaild address\n", acaddr);
			exit(-1);
		}
	} else {
		getip(nic, &gconf.addr);
	}
	gconf.addr.sin_port = htons(port);
	gconf.addr.sin_family = AF_INET;
	sys_info("nic: %s, mac: %s addr: %s, port: %d\n",
		nic, mac_to_macstr(gconf.mac, macstr), 
		inet_ntoa(gconf.addr.sin_addr), port);
}
#else
static in_addr_t r_server(char *acaddr)
{
	struct hostent *host;
	host = gethostbyname(acaddr);
	if(host != NULL && host->h_length > 0)
		return *(in_addr_t *)host->h_addr_list[0];

	sys_err("Can not parse:%s\n", acaddr);
	exit(-1);
}

void gconf_init(char *nic, char *acaddr, int port)
{
	getmac(nic, &gconf.mac[0]);
	if(acaddr && strlen(acaddr) != 0) {
		gconf.acaddr.sin_addr.s_addr = r_server(acaddr);
		gconf.acaddr.sin_port = htons(port);
	}
}
#endif
